package first.group.ssh.writebuffer;

import first.group.ssh.util.ByteBufferUtil;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ByteBufferContent extends WriteContent {
    private final ByteBuffer content;
    
    public ByteBufferContent(ByteBuffer content) {
        this(content, false);
    }
    
    public ByteBufferContent(ByteBuffer content, boolean copy) {
        if (copy) {
            this.content = ByteBufferUtil.copyCompatedByteBuffer(content);
        } else {
            this.content = content.duplicate();
        }
    }
    
    @Override
    public int write(SocketChannel channel) throws IOException {
        return channel.write(content);
    }

    @Override
    public int write(ByteBuffer buffer) {
        var writeSize = Math.min(buffer.remaining(), content.remaining());
        var origLimit = buffer.limit();
        content.limit(content.position() + writeSize);
        buffer.put(content);
        content.limit(origLimit);
        return writeSize;
    }

    @Override
    public boolean hasRemaining() {
        return content.hasRemaining();
    }

    @Override
    public int getRemaining() {
        return content.remaining();
    }
}
